package com.fr.chicken.service.Impl;



import com.fr.chicken.facade.base.BaseResponseDTO;
import com.fr.chicken.service.UploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;


@Service("uploadService")
public class UploadServiceImpl implements UploadService {

    @Override
    public BaseResponseDTO uploadImg(MultipartFile multipartFile) {
        BaseResponseDTO responseDTO = new BaseResponseDTO();
        if (multipartFile.isEmpty() || StringUtils.isBlank(multipartFile.getOriginalFilename())) {
            responseDTO.faild();
            responseDTO.setMsg("上传失败");
            return responseDTO;
        }
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            responseDTO.faild();
            responseDTO.setMsg("上传失败");
            return responseDTO;
        }
        String filePath = "C:\\chicken\\images";

        String file_name = null;
        try {
            file_name = saveImg(multipartFile, filePath);
            if (StringUtils.isNotBlank(file_name)) {
                responseDTO.success();
                responseDTO.setMsg("上传成功");
                return responseDTO;
            }
            responseDTO.faild();
            responseDTO.setMsg("上传失败");
            return responseDTO;
        } catch (IOException e) {
            responseDTO.faild();
            responseDTO.setMsg("上传失败");
            return responseDTO;
        }
    }
    /**
     * 保存图片，直接以multipartFile形式
     *
     * @param multipartFile
     * @param path          图片保存绝对路径
     * @return 返回图片名
     * @throws IOException
     */
    public static String saveImg(MultipartFile multipartFile, String path) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        String fileName = multipartFile.getOriginalFilename();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        return fileName;
    }
}
